package org.janzen_zhang.androidftp;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Janzen on 16-7-15.
 */
public class CopyFileFromAssets {
    private static final String TAG = "CopyFileFromAssets";
    /**
     *
     * @param myContext
     * @param ASSETS_NAME 要复制的文件名
     * @param savePath 要保存的路径
     * @param saveName 复制后的文件名
     */

    public static void copy(Context myContext, String ASSETS_NAME,
                            String savePath, String saveName) {
        String filename = savePath + "/" + saveName;

        File dir = new File(savePath);
        // 如果目录不中存在，创建这个目录
        if (!dir.exists()) {
            Log.d(TAG, "make directory: " + dir.getAbsolutePath());
            dir.mkdir();
        }
        try {
            File file = new File(filename);
            if (!file.exists()) {
                file.createNewFile();
                InputStream is = myContext.getResources().getAssets()
                        .open(ASSETS_NAME);
                FileOutputStream fos = new FileOutputStream(filename);
                byte[] buffer = new byte[7168];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
        } catch (Exception e) {
            Log.d(TAG, Log.getStackTraceString(e));
            e.printStackTrace();
        }
    }
    public void testCopy(Context context) {
        String path=context.getFilesDir().getAbsolutePath();
        String name="test.txt";
        CopyFileFromAssets.copy(context, name, path, name);
    }

    public static void copyAssetsDataToSD(Context context, String assertName, String strOutFileName){
        InputStream myInput;
        OutputStream myOutput = null;
        try {
            myOutput = new FileOutputStream(strOutFileName);
            myInput = context.getAssets().open(assertName);
            byte[] buffer = new byte[1024];
            int length = myInput.read(buffer);
            while(length > 0) {
                myOutput.write(buffer, 0, length);
                length = myInput.read(buffer);
            }

            myOutput.flush();
            myInput.close();
            myOutput.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, Log.getStackTraceString(e));
        }

    }
}
